package cn.broadmax.boot.modules.sys.service.impl;

import cn.broadmax.boot.modules.sys.entity.SysRoleResource;
import cn.broadmax.boot.modules.sys.mapper.SysRoleResourceMapper;
import cn.broadmax.boot.modules.sys.service.ISysRoleResourceService;
import cn.broadmax.boot.util.Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jexx.util.CollectionUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色资源 服务实现类
 * </p>
 *
 * @author jexx
 * @since 2020-07-21
 */
@Service
public class SysRoleResourceServiceImpl extends ServiceImpl<SysRoleResourceMapper, SysRoleResource> implements ISysRoleResourceService {

    @Override
    public List<SysRoleResource> getRoleResourcesByRoleId(String roleId) {
        LambdaQueryWrapper<SysRoleResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleResource::getRoleId, roleId);
        return super.list(wrapper);
    }

    @Override
    public boolean updateResourcesByRoleId(String roleId, List<String> resourceIds) {
        List<SysRoleResource> existRoleResources = getRoleResourcesByRoleId(roleId);

        //移除
        Set<SysRoleResource> removeRoleResources = Utils.findLeftDiff(existRoleResources, SysRoleResource::getResourceId,
                resourceIds, s->s);
        if(CollectionUtil.isNotEmpty(removeRoleResources)){
            List<String> removeIds = removeRoleResources.stream().map(SysRoleResource::getId).collect(Collectors.toList());
            super.removeByIds(removeIds);
        }

        //新增
        Set<String> saveResourceIds = Utils.findLeftDiff(resourceIds, s->s, existRoleResources, SysRoleResource::getResourceId);
        if(CollectionUtil.isNotEmpty(saveResourceIds)){
            List<SysRoleResource> saveRoleResources = new ArrayList<>();
            for(String resourceId : saveResourceIds){
                SysRoleResource roleResource = new SysRoleResource();
                roleResource.setRoleId(roleId);
                roleResource.setResourceId(resourceId);
                saveRoleResources.add(roleResource);
            }
            super.saveBatch(saveRoleResources);
        }
        return true;
    }
}
